<?php

namespace App\Api\Controllers\CustomerApplets;

use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Api\Controllers\CustomerApplets\BaseController;
use App\Api\Controllers\CustomerApplets\CouponController;
use App\Api\Controllers\CustomerApplets\CouponAliPayController;
use App\Models\CustomerAppletsUserOrders;
use Illuminate\Support\Facades\DB;

use App\Api\Controllers\Merchant\OrderController as MerchantOrderController;

class OrderController extends BaseController
{

    /**
     * 查询订单数据
     * 分页量：20
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderData(Request $request){

        $requestAllData = $request->all();

        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> getOrderData($requestAllData['user_id'],$requestAllData['store_id'],isset($requestAllData['order_pay_status']) ? $requestAllData['order_pay_status']:"all");

        return $this->responseDataJson(200,"查询成功",$result);
    }

    /**
     * 查询订单详情信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderDetailData(Request $request){

        $requestAllData = $request->all();

        if(!isset($requestAllData['order_id']) || empty($requestAllData['order_id'])){
            return $this->responseDataJson(202,"订单id参数未定义");
        }

        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> getOrderDetailData($requestAllData['user_id'],$requestAllData['store_id'],$requestAllData['order_id']);

        return $this->responseDataJson(200,"查询成功",$result);

    }

    /**
     * 生成支付订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function generateOrderData(Request $request){

        $requestAllData = $request->all();

        if(!isset($requestAllData['order_type']) || empty($requestAllData['order_type'])){
            return $this->responseDataJson(202,"订单类型参数未定义");
        }
        switch ($requestAllData['terminal_type']){
            //微信
            case config("api.weChat"):
                if(!isset($requestAllData['out_trade_no']) || empty($requestAllData['out_trade_no'])){
                    $request_id = date("YmdHis").time().rand(1,10000);
                    $requestAllData['out_trade_no'] = "wx_".$request_id;
                }
                break;
            //支付宝
            case config("api.aliPay"):
                if(!isset($requestAllData['out_trade_no']) || empty($requestAllData['out_trade_no'])){
                    $request_id = date("YmdHis").time().rand(1,10000);
                    $requestAllData['out_trade_no'] = "ali_".$request_id;
                }
                break;
        }

        //说明是外卖订单
        if (!isset($requestAllData['code_order_type'])){
            if($requestAllData['order_type'] == 1){
                if(!isset($requestAllData['address_id']) || empty($requestAllData['address_id'])){
                    return $this->responseDataJson(202,"收货地址不可为空");
                }
                if(!isset($requestAllData['delivery_method']) || empty($requestAllData['delivery_method'])){
                    return $this->responseDataJson(202,"配送方式不可为空");
                }
            }else{
                if(!isset($requestAllData['self_raising_order_mobile']) || empty($requestAllData['self_raising_order_mobile'])){
                    return $this->responseDataJson(202,"预留取货手机号不可为空");
                }
            }

            if(!isset($requestAllData['self_raising_order_time']) || empty($requestAllData['self_raising_order_time'])){
                return $this->responseDataJson(202,"时间不可为空");
            }

            if(!isset($requestAllData['is_use_coupon']) || empty($requestAllData['is_use_coupon'])){
                return $this->responseDataJson(202,"is_use_coupon参数不可为空");
            }

            if($requestAllData['is_use_coupon'] == 1){
                if(!isset($requestAllData['coupon_id']) || empty($requestAllData['coupon_id'])){
                    return $this->responseDataJson(202,"优惠券id参数不可为空");
                }
                if(!isset($requestAllData['coupon_source']) || empty($requestAllData['coupon_source'])){
                    return $this->responseDataJson(202,"优惠券来源参数不可为空");
                }
                if(!isset($requestAllData['use_coupon_money']) || empty($requestAllData['use_coupon_money'])){
                    return $this->responseDataJson(202,"优惠券额度不可为空");
                }
            }

            if(!isset($requestAllData['order_total_money']) || empty($requestAllData['order_total_money'])){
                return $this->responseDataJson(202,"订单总金额不可为空");
            }

            if(!isset($requestAllData['order_pay_money']) || empty($requestAllData['order_pay_money'])){
                return $this->responseDataJson(202,"订单实际支付金额不可为空");
            }

            if(!isset($requestAllData['user_pay_type']) || empty($requestAllData['user_pay_type'])){
                return $this->responseDataJson(202,"支付方式不可为空");
            }
        }

        // 如果是扫码点餐,code_order_type == 1说明是扫码点餐
        if (isset($requestAllData['code_order_type'])) {
            if ($requestAllData['code_order_type'] == 1 && empty($requestAllData['table_id'])) {
                return $this->responseDataJson(202,"桌号不可为空");
            }
        }

        //说明用户使用的是余额支付
        /**
        if($requestAllData['user_pay_type'] == 1){
            switch ($requestAllData['terminal_type']){
                //微信
                case config("api.weChat"):
                    if(!isset($requestAllData['openid']) || empty($requestAllData['openid'])){
                        return $this->responseDataJson(202,"用户openid不可为空");
                    }
                    //用户的余额数据
                    $userMemberList = DB::table("member_lists")->select("mb_money","pay_counts","pay_moneys","updated_at","xcx_openid","wx_openid","ali_user_id")
                        ->where(['xcx_openid' => $requestAllData['openid']])->first();
                    if(!empty($userMemberList)){
                        $mb_money = number_format($userMemberList->mb_money,2);
                        $order_pay_money = number_format($requestAllData['order_pay_money'],2);
                        if($mb_money < $order_pay_money){
                            return $this->responseDataJson(202,"用户余额不足");
                        }
                    }else{
                        return $this->responseDataJson(202,"用户余额数据不存在");
                    }
                    break;
                //支付宝
                case config("api.aliPay"):
                    if(!isset($requestAllData['openid']) || empty($requestAllData['openid'])){
                        return $this->responseDataJson(202,"用户openid不可为空");
                    }
                    //用户的余额数据
                    $userMemberList = DB::table("member_lists")->select("mb_money","pay_counts","pay_moneys","updated_at","xcx_openid","wx_openid","ali_user_id")
                        ->where(['ali_user_id' => $requestAllData['openid']])->first();
                    if(!empty($userMemberList)){
                        $mb_money = number_format($userMemberList->mb_money,2);
                        $order_pay_money = number_format($requestAllData['order_pay_money'],2);
                        if($mb_money < $order_pay_money){
                            return $this->responseDataJson(202,"用户余额不足");
                        }
                    }else{
                        return $this->responseDataJson(202,"用户余额数据不存在");
                    }
                    break;
            }
        }
         **/

        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> generateOrderData($requestAllData);

        if($result['status'] == 200){
            //核销卡券
            switch ($requestAllData['terminal_type']){
                //微信数据
                case config("api.weChat"):
                    if($requestAllData['is_use_coupon'] == 1){
                        Log::info("开始核销微信卡券：");
                        if(isset($requestAllData['coupon_id']) && !empty($requestAllData['coupon_id'])){
                            $couponController = new CouponController();
                            $couponResult = $couponController->userUseCoupon($requestAllData['coupon_id'],$requestAllData['store_id'],$requestAllData['user_id']);
                        }
                    }
                    break;
                //支付宝数据
                case config("api.aliPay"):
                    if($requestAllData['is_use_coupon'] == 1){
                        Log::info("开始核销支付宝卡券：");
                        if(isset($requestAllData['coupon_id']) && !empty($requestAllData['coupon_id'])){
                            $couponAliPayController = new CouponAliPayController();
                            $couponResult = $couponAliPayController->userUseAliPayCoupon($requestAllData['coupon_id'],$requestAllData['store_id'],$requestAllData['user_id']);
                        }
                    }
                    break;
            }
            return $this->responseDataJson($result['status'],"生成订单成功",$result['message']);
        }else{
            return $this->responseDataJson($result['status'],$result['message'],"");
        }
    }


    /**
     * 查询商家订单的今日统计量
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreOrder(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id参数不可为空");
        }

        $storeOrder = DB::table("customerapplets_user_orders")
            ->where(['store_id' => $requestAllData['store_id']])
            ->where('created_at','>',date("Y-m-d").' 00:00:00')->where('created_at','<=',date("Y-m-d").' 23:59:59')
            ->get();

        $order_total_money = 0;

        $order_number      = 0;

        if(!empty($storeOrder)){
            foreach ($storeOrder as $key => $val){
                $order_total_money = $order_total_money + $val->order_total_money;
                $order_number      = $order_number + 1;
            }
        }

        return $this->responseDataJson(200,"查询成功",[
            'order_total_money' => $order_total_money,
            'order_number'      => $order_number
        ]);
    }

    /**
     * 商家获取订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreOrderData(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id参数不可为空");
        }
        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> getStoreOrderData($requestAllData['store_id'],isset($requestAllData['created_at']) ? $requestAllData['created_at'] : "",isset($requestAllData['out_trade_no']) ? $requestAllData['out_trade_no'] : "",isset($requestAllData['order_pay_status']) ? $requestAllData['order_pay_status'] : "");

        return $this->responseDataJson(200,"查询成功",$result);

    }

    /**
     * 商家更新订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateStoreOrderData(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id参数不可为空");
        }
        if(!isset($requestAllData['order_id']) || empty($requestAllData['order_id'])){
            return $this->responseDataJson(202,"order_id参数不可为空");
        }
        if(!isset($requestAllData['out_trade_no']) || empty($requestAllData['out_trade_no'])){
            return $this->responseDataJson(202,"out_trade_no参数不可为空");
        }
        if(!isset($requestAllData['order_pay_status']) || empty($requestAllData['order_pay_status'])){
            return $this->responseDataJson(202,"order_pay_status参数不可为空");
        }

        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> updateStoreOrderData($requestAllData['store_id'],$requestAllData['order_id'],$requestAllData['out_trade_no'],$requestAllData['order_pay_status']);

        if($result['status'] == 200){
            return $this->responseDataJson(200,"更新成功","");
        }else{
            return $this->responseDataJson(202,"更新失败",$result['message']);
        }
    }

    /**
     * 用户退款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userRefundOrder(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id参数不可为空");
        }
        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(202,"user_id参数不可为空");
        }

        if(!isset($requestAllData['out_trade_no']) || empty($requestAllData['out_trade_no'])){
            return $this->responseDataJson(202,"订单号不可为空");
        }
        if(!isset($requestAllData['refund_amount']) || empty($requestAllData['refund_amount'])){
            return $this->responseDataJson(202,"退款金额不可为空");
        }

        $storeInfo = DB::table("stores")->where(['store_id' => $requestAllData['store_id']])->first();

        if(empty($storeInfo)){
            return $this->responseDataJson(202,"该门店信息不存在","");
        }

        $requestAllData['merchant_id'] = $storeInfo->merchant_id;

        $MerchantOrderController = new MerchantOrderController();
        $result = $MerchantOrderController->refund_public($requestAllData);
        $result = json_decode($result,true);
        if($result['status'] == 2){
            return $this->responseDataJson(200,"退款成功","");
        }else{
            return $this->responseDataJson(202,$result['message'],"");
        }
    }

    /**
     * 用户更新订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUserOrderData(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id参数不可为空");
        }
        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(202,"user_id参数不可为空");
        }
        if(!isset($requestAllData['order_id']) || empty($requestAllData['order_id'])){
            return $this->responseDataJson(202,"order_id参数不可为空");
        }
        if(!isset($requestAllData['out_trade_no']) || empty($requestAllData['out_trade_no'])){
            return $this->responseDataJson(202,"订单号不可为空");
        }
        if(!isset($requestAllData['order_pay_status']) || empty($requestAllData['order_pay_status'])){
            return $this->responseDataJson(202,"订单状态不可为空");
        }

        $customerAppletsUserOrderModel = new CustomerAppletsUserOrders();

        $result = $customerAppletsUserOrderModel -> updateStoreOrderData($requestAllData['store_id'],$requestAllData['order_id'],$requestAllData['out_trade_no'],$requestAllData['order_pay_status'],$requestAllData);

        if($result['status'] == 200){
            return $this->responseDataJson(200,"更新成功","");
        }else{
            return $this->responseDataJson(202,"更新失败",$result['message']);
        }
    }

    /**
     * 完成订单支付
     */
    public function donePayOrder(Request $request)
    {
        $input = $request->all();
        $model = new CustomerAppletsUserOrders();

        if (empty($input['order_id'])) {
            return $this->responseDataJson(202,"order_id参数不可为空");
        }

        // 先查询有无这笔订单
        $orderInfo = $model->getOrderInfo($input);
        if (empty($orderInfo)) {
            return $this->responseDataJson(202,"暂无数据");
        }

        $updateData = [
            'out_trade_no' => $input['out_trade_no'],
            'order_pay_status' => 1,
            'updated_at' => date('Y-m-d h:i:s', time()),
        ];

        $res = $model->donePayOrder($input, $updateData);
        if ($res) {
            return $this->responseDataJson(200,"更新成功");
        } else {
            return $this->responseDataJson(202,"更新失败");
        }

    }

}
